package edu.zju.gis.dbfg.model.util;

import scala.Tuple2;

import java.io.FileWriter;
import java.io.File;
import java.io.IOException;
import java.util.*;

public class WriteToFile {
    public static void writeToFile(FileWriter writer,Map<String, GeoItem> result) throws IOException{

        List<String> dlbm_list=new ArrayList<>();
        //writer.write(String.format("%s\t%s\t%s\n", zldwdm2, dlbm2, area2));
        Map<String,List<Tuple2<String,Double>>> result_dic=new Hashtable<>() ;
        //String dlbm_string="0101,0102,0103,0201,0202,0203,0204,0301,0302,0305,0307,0401,0403,0404,05H1,0508,0601";
        for (String key : result.keySet()) {
            String[] fields = key.split("##");
            String zldwdm = fields[0];
            String dlbm = fields[1];
            GeoItem gi = result.get(key);
            Double area = (Double) gi.getProp().get("AREA");
            List<Tuple2<String,Double>> dlbm_string=new ArrayList<>();
            if(!dlbm_list.contains(dlbm)){
                dlbm_list.add(dlbm);
            }
            if(! result_dic.containsKey(zldwdm))
            {
                Tuple2<String,Double> tu=new Tuple2<>(dlbm,area);
                dlbm_string.add(tu);
                result_dic.put(zldwdm,dlbm_string);
            }
            else{
                Tuple2<String,Double> tu=new Tuple2<>(dlbm,area);
                dlbm_string=result_dic.get(zldwdm);
                dlbm_string.add(tu);
                result_dic.put(zldwdm,dlbm_string);
            }
            //String dlbm = (String) gi.getProp().get("DLBM");
//            String s = String.format("%s\t%s\t%.9f", zldwdm, dlbm, area);
//            writer.write(s + "\n");
        }
        Collections.sort(dlbm_list);
        String s="ZLDWDM\t";
        for(int i=0;i<dlbm_list.size();i++){
            s=s+dlbm_list.get(i)+"\t";
        }
        writer.write(s + "\n");
        //Map<String, String> sortMap = new TreeMap<String, String>(new MapKeyComparator());
        //sortMap.putAll(result_dic);
        for(String key : result_dic.keySet()){
            List<Tuple2<String,Double>> test=result_dic.get(key);
            String out=key+"\t";
            for(int i=0;i<dlbm_list.size();i++){
                int flag=0;
                for(int j=0;j<test.size();j++){
                    if(test.get(j)._1.equals(dlbm_list.get(i))){
                        out=out+String.format("%.9f\t", test.get(j)._2);
                        flag=1;
                        continue;
                    }
                }
                if(flag==0){
                    out=out+"0.000000000\t";
                }
            }
            writer.write(out + "\n");

        }
        writer.flush();

    }
}
